<template>
  <div class="app-container">
    <!-- 搜索/过滤区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item label="标签名称">
          <el-input v-model="searchForm.name" placeholder="请输入标签名称" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="标签分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px;">
            <el-option v-for="category in categoryOptions" :key="category.value" :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="启用" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="operation-text">查询</el-button>
          <el-button @click="handleReset" class="operation-text">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus" class="operation-text">新增标签</el-button>
      <el-button type="success" @click="handleBatchEnable" :disabled="!selectedRows.length" icon="el-icon-check"
        class="operation-text">批量启用</el-button>
      <el-button type="warning" @click="handleBatchDisable" :disabled="!selectedRows.length" icon="el-icon-close"
        class="operation-text">批量停用</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length" icon="el-icon-delete"
        class="operation-text">批量删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange"
      style="width: 100%; margin-bottom: 20px;" border stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="标签名称" width="150" />
      <el-table-column prop="category" label="标签分类" width="120">
        <template slot-scope="scope">
          <el-tag :type="getCategoryTagType(scope.row.category)" size="small">
            {{ getCategoryLabel(scope.row.category) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="标签描述" min-width="200" />
      <el-table-column prop="usageCount" label="使用次数" width="100" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="'1'" :inactive-value="'0'" active-color="#13ce66"
            inactive-color="#ff4949" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)" class="operation-text">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" style="color: #F56C6C;"
            class="operation-text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" background />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
      @close="handleDialogClose">
      <el-form :model="tagForm" :rules="rules" ref="tagForm" label-width="100px" size="small">
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="标签分类" prop="category">
          <el-select v-model="tagForm.category" placeholder="请选择标签分类" style="width: 100%;">
            <el-option v-for="category in categoryOptions" :key="category.value" :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签描述" prop="description">
          <el-input v-model="tagForm.description" type="textarea" :rows="3" placeholder="请输入标签描述" maxlength="200"
            show-word-limit />
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="tagForm.color" />
          <span class="color-tip">选择标签显示颜色</span>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="tagForm.sort" :min="0" :max="999" controls-position="right" style="width: 120px;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="tagForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'NurseTagManage',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        category: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 选中的行
      selectedRows: [],
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增标签',
      submitLoading: false,
      // 标签表单
      tagForm: {
        id: null,
        name: '',
        category: '',
        description: '',
        color: '#409EFF',
        sort: 0,
        status: '1'
      },
      // 标签分类选项
      categoryOptions: [
        { label: '专业技能', value: 'skill' },
        { label: '擅长领域', value: 'expertise' },
        { label: '性格特点', value: 'personality' },
        { label: '工作经验', value: 'experience' },
        { label: '教育背景', value: 'education' },
        { label: '其他', value: 'other' }
      ],
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择标签分类', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入标签描述', trigger: 'blur' },
          { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序值', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadData()
    this.loadCategoryData()
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }

        // 模拟API调用，实际项目中替换为真实API
        const response = await this.mockApiCall(params)
        this.tableData = response.data
        this.pagination.total = response.total
      } catch (error) {
        this.$message.error('加载数据失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // 加载分类数据
    async loadCategoryData() {
      try {
        // 实际项目中调用 getTagCategoryList()
        // const response = await getTagCategoryList()
        // this.categoryOptions = response.data
      } catch (error) {
        console.error('加载分类数据失败:', error)
      }
    },

    // 模拟API调用（实际项目中删除此方法）
    mockApiCall(params) {
      return new Promise((resolve) => {
        setTimeout(() => {
          const mockData = [
            {
              id: 1,
              name: '静脉穿刺',
              category: 'skill',
              description: '熟练掌握各种静脉穿刺技术，包括外周静脉、中心静脉等',
              usageCount: 0,
              status: '1',
              color: '#409EFF',
              sort: 1,
              createTime: '2025-08-15 10:30:00'
            },
            {
              id: 2,
              name: '新生儿护理',
              category: 'expertise',
              description: '专业从事新生儿护理工作，具备丰富的临床经验',
              usageCount: 1,
              status: '1',
              color: '#67C23A',
              sort: 2,
              createTime: '2025-08-14 14:20:00'
            },
            {
              id: 3,
              name: '耐心细致',
              category: 'personality',
              description: '工作态度耐心细致，能够细致入微地照顾患者',
              usageCount: 2,
              status: '1',
              color: '#E6A23C',
              sort: 3,
              createTime: '2025-08-13 09:15:00'
            },
            {
              id: 4,
              name: 'ICU护理',
              category: 'experience',
              description: '具备重症监护室护理经验，熟悉各种监护设备操作',
              usageCount: 0,
              status: '0',
              color: '#F56C6C',
              sort: 4,
              createTime: '2025-08-12 16:45:00'
            },
            {
              id: 5,
              name: '护理学本科',
              category: 'education',
              description: '护理学专业本科学历，具备扎实的理论基础',
              usageCount: 0,
              status: '1',
              color: '#909399',
              sort: 5,
              createTime: '2025-08-11 11:30:00'
            }
          ]

          // 模拟搜索过滤
          let filteredData = mockData
          if (params.name) {
            filteredData = filteredData.filter(item =>
              item.name.includes(params.name)
            )
          }
          if (params.category) {
            filteredData = filteredData.filter(item =>
              item.category === params.category
            )
          }
          if (params.status !== '') {
            filteredData = filteredData.filter(item =>
              item.status === params.status
            )
          }

          // 模拟分页
          const start = (params.page - 1) * params.size
          const end = start + params.size
          const paginatedData = filteredData.slice(start, end)

          resolve({
            data: paginatedData,
            total: filteredData.length
          })
        }, 500)
      })
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: '',
        category: '',
        status: ''
      }
      this.handleSearch()
    },

    // 新增标签
    handleAdd() {
      this.dialogTitle = '新增标签'
      this.tagForm = {
        id: null,
        name: '',
        category: '',
        description: '',
        color: '#409EFF',
        sort: 0,
        status: '1'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.tagForm && this.$refs.tagForm.clearValidate()
      })
    },

    // 编辑标签
    handleEdit(row) {
      this.dialogTitle = '编辑标签'
      this.tagForm = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.tagForm && this.$refs.tagForm.clearValidate()
      })
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.tagForm.validate(async (valid) => {
        if (!valid) return

        this.submitLoading = true
        try {
          if (this.tagForm.id) {
            // 编辑
            // await updateNurseTag(this.tagForm.id, this.tagForm)
            this.$message.success('更新成功')
          } else {
            // 新增
            // await createNurseTag(this.tagForm)
            this.$message.success('新增成功')
          }

          this.dialogVisible = false
          this.loadData()
        } catch (error) {
          this.$message.error('操作失败')
          console.error(error)
        } finally {
          this.submitLoading = false
        }
      })
    },

    // 处理状态变化
    async handleStatusChange(row) {
      try {
        const action = row.status === '1' ? '启用' : '停用'
        await this.$confirm(`确定要${action}该标签吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 调用相应的API
        if (row.status === '1') {
          // await enableNurseTag(row.id)
          this.$message.success('启用成功')
        } else {
          // await disableNurseTag(row.id)
          this.$message.success('停用成功')
        }

        // 重新加载数据以更新使用次数等信息
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          // 如果操作失败，恢复原来的状态
          row.status = row.status === '1' ? '0' : '1'
          this.$message.error('操作失败')
          console.error(error)
        } else {
          // 用户取消操作，恢复原来的状态
          row.status = row.status === '1' ? '0' : '1'
        }
      }
    },

    // 删除标签
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该标签吗？删除后不可恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // await deleteNurseTag(row.id)
        this.$message.success('删除成功')
        this.loadData()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
          console.error(error)
        }
      }
    },

    // 批量启用
    async handleBatchEnable() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要启用的标签')
        return
      }

      try {
        await this.$confirm(`确定要启用选中的 ${this.selectedRows.length} 个标签吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 批量启用逻辑
        for (const row of this.selectedRows) {
          // await enableNurseTag(row.id)
          row.status = '1' // 直接更新表格中的状态
        }

        this.$message.success('批量启用成功')
        this.selectedRows = []
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量启用失败')
          console.error(error)
        }
      }
    },

    // 批量停用
    async handleBatchDisable() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要停用的标签')
        return
      }

      try {
        await this.$confirm(`确定要停用选中的 ${this.selectedRows.length} 个标签吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 批量停用逻辑
        for (const row of this.selectedRows) {
          // await disableNurseTag(row.id)
          row.status = '0' // 直接更新表格中的状态
        }

        this.$message.success('批量停用成功')
        this.selectedRows = []
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量停用失败')
          console.error(error)
        }
      }
    },

    // 批量删除
    async handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要删除的标签')
        return
      }

      try {
        await this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 个标签吗？删除后不可恢复！`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        // 批量删除逻辑
        for (const row of this.selectedRows) {
          // await deleteNurseTag(row.id)
        }

        this.$message.success('批量删除成功')
        this.loadData()
        this.selectedRows = []
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('批量删除失败')
          console.error(error)
        }
      }
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadData()
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.tagForm && this.$refs.tagForm.resetFields()
    },

    // 获取分类标签类型
    getCategoryTagType(category) {
      const typeMap = {
        skill: 'primary',
        expertise: 'success',
        personality: 'warning',
        experience: 'info',
        education: 'danger',
        other: ''
      }
      return typeMap[category] || ''
    },

    // 获取分类标签文本
    getCategoryLabel(category) {
      const option = this.categoryOptions.find(item => item.value === category)
      return option ? option.label : category
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;

  .page-title {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }

  .page-desc {
    margin: 0;
    color: #909399;
    font-size: 14px;
  }
}

.search-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;

  .el-button {
    margin-right: 10px;
  }
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
}

.operation-text {
  font-size: 14px;
}

.color-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

// 表格样式优化
.el-table {
  .el-table__header-wrapper {
    th {
      background-color: #fafafa;
      color: #606266;
      font-weight: 600;
    }
  }
}

// 标签样式
.el-tag {
  margin-right: 5px;
}

// 开关样式优化
.el-switch {
  .el-switch__label {
    font-size: 12px;
  }

  &.is-checked {
    .el-switch__label {
      color: #13ce66;
    }
  }

  .el-switch__label--left {
    color: #ff4949;
  }
}
</style>